import { useState } from 'react';

interface CEQResponse {
  resp_code: string;
  balance: string;
  card_stat: string;
  trans_sn: string;
  error_msg: string;
}

export default function CEQQuery() {
  const [pan, setPan] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<CEQResponse | null>(null);
  const [error, setError] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setResult(null);

    try {
      const response = await fetch('/api/ceq', {  // 修改为相对路径
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          pan,
          appid: '01',
        }),
      });

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      setResult(data);
    } catch (err) {
      setError(err instanceof Error ? err.message : '查询失败，请稍后重试');
      console.error('查询出错:', err);
    } finally {
      setLoading(false);
    }
  };

  const formatBalance = (balance: string) => {
    const amount = parseInt(balance, 10) / 100;
    return amount.toFixed(2);
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-50 py-12 px-4 sm:px-6 lg:px-8">
      <div className="max-w-md mx-auto">
        {/* 卡片容器 */}
        <div className="bg-white rounded-2xl shadow-xl overflow-hidden backdrop-blur-lg backdrop-filter">
          {/* 卡片头部 */}
          <div className="px-8 py-6 bg-gradient-to-r from-indigo-600 to-blue-500">
            <h2 className="text-2xl font-bold text-white text-center">
              卡余额查询
            </h2>
          </div>

          {/* 卡片内容 */}
          <div className="px-8 py-6">
            <form onSubmit={handleSubmit} className="space-y-6">
              <div>
                <label htmlFor="pan" className="block text-sm font-medium text-gray-700">
                  卡号
                </label>
                <div className="mt-1 relative rounded-md shadow-sm">
                  <input
                    type="text"
                    id="pan"
                    value={pan}
                    onChange={(e) => setPan(e.target.value)}
                    className="block w-full px-4 py-3 rounded-lg border-2 border-gray-200 focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition duration-150 ease-in-out"
                    placeholder="请输入卡号"
                    required
                    maxLength={19}
                  />
                </div>
              </div>

              <button
                type="submit"
                disabled={loading}
                className={`w-full flex justify-center items-center px-6 py-3 border border-transparent text-base font-medium rounded-lg text-white ${
                  loading
                    ? 'bg-indigo-400 cursor-not-allowed'
                    : 'bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transform hover:scale-105 transition-all duration-150'
                }`}
              >
                {loading ? (
                  <>
                    <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    查询中...
                  </>
                ) : (
                  '查询'
                )}
              </button>
            </form>

            {error && (
              <div className="mt-6 rounded-lg bg-red-50 border-l-4 border-red-400 p-4">
                <div className="flex">
                  <div className="flex-shrink-0">
                    <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                      <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                    </svg>
                  </div>
                  <div className="ml-3">
                    <p className="text-sm text-red-700">{error}</p>
                  </div>
                </div>
              </div>
            )}

            {result && (
              <div className="mt-6 bg-white rounded-lg overflow-hidden divide-y divide-gray-200">
                <div className="px-4 py-5">
                  <div className="flex items-center justify-between">
                    <span className="text-sm font-medium text-gray-500">交易状态</span>
                    <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
                      result.resp_code === '0'
                        ? 'bg-green-100 text-green-800'
                        : 'bg-red-100 text-red-800'
                    }`}>
                      {result.resp_code === '0' ? '交易成功' : result.error_msg}
                    </span>
                  </div>
                </div>

                {result.resp_code === '0' && (
                  <>
                    <div className="px-4 py-5">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-500">卡余额</span>
                        <span className="text-lg font-semibold text-indigo-600">
                          ¥ {formatBalance(result.balance)}
                        </span>
                      </div>
                    </div>

                    <div className="px-4 py-5">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-500">卡状态</span>
                        <span className={`inline-flex items-center px-3 py-1 rounded-full text-sm font-medium ${
                          result.card_stat === '00'
                            ? 'bg-green-100 text-green-800'
                            : 'bg-yellow-100 text-yellow-800'
                        }`}>
                          {result.card_stat === '00' ? '正常' : `异常(${result.card_stat})`}
                        </span>
                      </div>
                    </div>

                    <div className="px-4 py-5">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium text-gray-500">交易流水号</span>
                        <span className="text-sm font-mono text-gray-900">{result.trans_sn}</span>
                      </div>
                    </div>
                  </>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
} 